<template>
  <div class="container">
    <nav-bar title="列表" />
    <div class="maintain">
      <scroll-category-line 
        class="sc-index category-list"
        :categories="categories" 
        :currentIndex="currentIndex" 
        @itemClicked="switchListLine" 
      />
      <!-- <img src='../../assets/img/belong-man-1.jpg' /> -->
      <img :src='banner' />
      <div class="info">
        <!-- <div class="dis">全场低至3折，保暖运动专场</div> -->
      </div>
      <!-- <div class="info">
        <div class="belong">主理人专场</div>
        <div class="name">冬季出新-冬季保暖保卫大战</div>
        <div class="dis">全场低至3折，保暖运动专场</div>
      </div> -->
    </div>
    <div class="products">
      <div class="tabs">
        <div class="item" @click="listByPrice">
          价格
          <i class="arrow up" :class="{'cur': priceOrderAsc}"></i>
          <i class="arrow dn" :class="{'cur': priceOrderDesc}"></i>
        </div>
        <div class="item" :class="{'item-cur': soldOrderAsc}" @click="listBySold">销量</div>
        <div class="item itemfilter" :class="{'item-bold': filterShow}" @click="filterList">
          筛选
          <i class="arrow up" :class="{'cur': filterShow}"></i>
        </div>
      </div>
      
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        offset="100"
        @load="onload"
      >
        <div class="list">
          <div 
            class="item" 
            v-for="(item, index) in productList" 
            :key="index"
            @click="goToProduct(item.ProductId)"
          >
            <div class="img">
              <img :src='item.ImagePath' @error="defaultImg(defaultImgUrl)" />
              <div class="labels">
                <i class="label label-ladder" v-if="item.IsOpenLadder">多件多折</i>
                <!-- <i class="label label-cutoff">券满300减50</i> -->
              </div>
            </div>
            <div class="name">{{item.ProductName}}</div>
            <div class="price">
              <h3>¥<span>{{item.MinSalePrice}}</span></h3>
              <h4 v-if="item.MinSalePrice!==item.MarketPrice">¥{{item.MarketPrice}}</h4>
            </div>
          </div>
        </div>
      </van-list>
        
        <!-- 为你推荐 -->
        <!-- <div 
          class="item" 
          v-for="(item, index) in productList" 
          :key="index"
          @click="goToProduct(item.ProductId)"
        >
          <div class="img"><img :src='item.ImagePath' @error="defaultImg(defaultImgUrl)" /></div>
          <div class="name">{{item.ProductName}}</div>
          <div class="price">
            <h3>¥<span>{{item.MinSalePrice}}</span></h3>
            <h4>¥{{item.SalePrice}}</h4>
          </div>
        </div> -->
      <div class="filter" v-show="filterShow">
        <div class="close" @click="close">&times;</div>
        <div class="item">
          <div class="sort">尺码</div>
          <div class="sort-list">
            <div 
              class="item" 
              :class="{itemon: item.checked}"
              v-for="(item, index) in attrSizeList" 
              :key="index"
              @click="checkSize(index)"
            >
              {{item.Name}}
            </div>
          </div>
        </div>
        <div class="item">
          <div class="sort">颜色</div>
          <div class="sort-list">
            <div 
              class="item" 
              :class="{itemon: item.checked}"
              v-for="(item, index) in attrColorList" 
              :key="index"
              @click="checkColor(index)"
            >
              {{item.Name}}
            </div>
          </div>
        </div>
        <div class="item">
          <div class="sort">优惠</div>
          <div class="sort-list">
            <div 
              class="item" 
              :class="{itemon: cutOff}"
              @click="checkCutoff"
            >
              促销
            </div>
          </div>
        </div>
      </div>
      <div class="btns" v-show="filterShow">
        <div class="btn" @click="reset">重置</div>
        <div class="btn btn-bg" @click="filterSubmit">确认</div>
      </div>
    </div>
  </div>
</template>

<script>
import NavBar from 'components/common/NavBar'
import { defaultImg } from '../../utils/'
import { getCategories, getShopCategories } from '../../network/best'
import { getProductList, getAttr } from '../../network/productList'
import ScrollCategoryLine from 'components/content/ScrollCategory'

export default {
  name: 'ProductList',
  components: {
    NavBar,
    ScrollCategoryLine
  },
  data() {
    return {
      loading: false,
      finished: false,
      pageNo: 1,
      pageSize: 10,
      defaultImgUrl: require('../../assets/img/recommand-none.png'),
      categoryId: '',
      sid: '',
      orderKey: 1,
      orderType: 1,
      productList: [],
      categories: [],
      currentIndex: 0,
      filterShow: false,
      attrSizeList: [],
      attrColorList: [],
      cutOff: false,
    }
  },
  computed: {
    attrSize(){
      let checkedList = this.attrSizeList.filter(item => item.checked)
      let checkedStr = checkedList.map(item => {
        item = item.Id
        return item
      }).join(',')
      return checkedStr
    },
    attrColor(){
      let checkedList = this.attrColorList.filter(item => item.checked)
      let checkedStr = checkedList.map(item => {
        item = item.Id
        return item
      }).join(',')
      return checkedStr
    },
    attrAll(){
      let checkedArr = []
      let checkedStr = ''
      let arr1 = this.attrSize ? this.attrSize.split(',') : []
      let arr2 = this.attrColor ? this.attrColor.split(',') : []
      arr1.map(item => {
        checkedArr.push(item)
      })
      arr2.map(item => {
        checkedArr.push(item)
      })
      checkedStr = checkedArr.join(',')
      return checkedStr
    },
    banner(){
      let imgsrc = ''
      let categoryItem = this.categories[this.currentIndex]
      if(categoryItem){
        imgsrc = categoryItem.Image
      }
      return imgsrc
    },
    priceOrderAsc(){
      return this.orderKey === 3 && this.orderType === 1
    },
    priceOrderDesc(){
      return this.orderKey === 3 && this.orderType === 2
    },
    soldOrderAsc(){
      return this.orderKey === 2 && this.orderType === 2
    }
  },
  async mounted() {
    this.categoryId = this.$route.query.cid
    this.sid = this.$route.query.sid
    this.getCategories()
    await this.getAttr()
  },
  methods: {
    onload(){
      this.getProductList()
    },
    close(){
      this.filterShow = false
    },
    getCategories(){
      // 获取所有产品分类
      getCategories(list => {
        // 记录分类所属
        list.map((item, index) => {
          item.sid = 0
          return item
        })  

        this.categories = list
        
        // 获取场景分类
        getShopCategories(list => {
          list = list.filter(item => item.Id != 350)
          list.map(item => {
            item.sid = 1
            return item
          })
          this.categories = [...this.categories, ...list]

          // 匹配当前分类名称
          this.categories.map((item,index) => {
            if(item.Id === this.categoryId){
              this.currentIndex = index
            } else {
              // 如果未匹配到一级分类，检查二级分类 
              item.SubCategories.map(itemIn => {
                if(itemIn.Id === this.categoryId){
                  this.currentIndex = index
                }
              })
            }
          })
        })

      })
    },
    getAttr(){
      return new Promise(resolve => {
        let requestData = {
          categoryId: 163, // 分类ID
        }
        getAttr(requestData, list => {
          this.attrSizeList = list[0].AttrValues
          this.attrColorList = list[1].AttrValues
          this.attrSizeList.map(item => {
            item.checked = false
            return item
          })
          this.attrColorList.map(item => {
            item.checked = false
            return item
          })
          resolve()
        })
      })
    },
    getAttrByCid(cid){
      return new Promise(resolve => {
        let requestData = {
          categoryId: cid, // 分类ID
        }
        getAttr(requestData, list => {
          resolve(list)
        })
      })
    },
    checkSize(index){
      this.attrSizeList = this.attrSizeList.map(item => {
        item.checked = false
        return item
      })

      this.attrSizeList[index].checked 
      = !this.attrSizeList[index].checked

      this.$set(this.attrSizeList, index, this.attrSizeList[index])
    },
    checkColor(index){
      this.attrColorList = this.attrColorList.map(item => {
        item.checked = false
        return item
      })
      
      this.attrColorList[index].checked 
      = !this.attrColorList[index].checked

      this.$set(this.attrColorList, index, this.attrColorList[index])
    },
    checkCutoff(){
      this.cutOff = !this.cutOff
    },
    filterSubmit(){
      this.reloadList()

      this.filterShow = false
    },
    reset(){
      this.attrSizeList = this.attrSizeList.map(item => {
        item.checked = false
        return item
      })
      this.attrColorList = this.attrColorList.map(item => {
        item.checked = false
        return item
      })
      this.cutOff = false
    },
    getProductList(){
      let requestData = {
        pageNo: this.pageNo,
        pageSize: this.pageSize,
        orderKey: this.orderKey, // 排序
        orderType: this.orderType, // 排序方式
        cid: this.categoryId, // 平台或商家分类ID
        sid: this.sid, // 0 - 平台分类ID || 1 - 商家分类ID
        a_id: this.attrAll, // 855,856,857 L S M
        cutOff: this.cutOff
      }
      getProductList(requestData, list => {
        list = list.map(item => {
          item.SalePrice = item.SalePrice.toFixed(2)
          item.MinSalePrice = item.MinSalePrice.toFixed(2)
          item.MarketPrice = item.MarketPrice.toFixed(2)
          return item
        })
        this.productList = [...this.productList, ...list]
        
        this.loading = false
        if(list.length < this.pageSize){
          this.finished = true
          return false
        }
        this.pageNo++
      })
    },
    async switchListLine(index){
      await this.getAttr()
      
      this.filterShow = false
      this.currentIndex = index
      this.categoryId = this.categories[this.currentIndex].Id
      this.sid = this.categories[this.currentIndex].sid
      
      this.reset()
      this.reloadList()

      
    },
    defaultImg(imgUrl){
      defaultImg(imgUrl)
    },
    filterList(){
      this.filterShow = !this.filterShow
    },
    listByPrice(){
      this.filterShow = false
      if(this.orderKey === 3){ // 重复点击
        this.orderType = this.orderType === 1 ? 2 : 1
      } else {
        this.orderType = 2
      }
      this.orderKey = 3

      this.reloadList()
    },
    listBySold(){
      this.filterShow = false
      if(this.orderKey === 2){ // 重复点击
        return false
        // this.orderType = this.orderType === 1 ? 2 : 1
      } else {
        this.orderType = 2
      }
      this.orderKey = 2

      this.reloadList()
    },
    goToProduct(id){
      this.$router.push({
        path: '/product',
        query: {
          id,
        }
      })
    },
    reloadList(){
      this.finished = true
      setTimeout(() => {
        this.pageNo = 1
        this.finished = false
        this.productList = []
      }, 0)
    }
  },
}
</script>

<style scoped>
.container{
  position: relative;
  background-color: #f2f2f2;
}
.maintain{
  position: relative;
}
.maintain img{
  width: 100%;
}
.maintain .info{
  position: absolute;
  left: 30px;
  bottom: 60px;
  color: #ffffff;
}
.maintain .info .belong{
  font-size: 12px;
}
.maintain .info .name{
  font-size: 16px;
  line-height: 2.5;
}
.maintain .info .dis{
  font-size: 12px;
}
.products{
  min-height: 700px;
  /* position: relative; */
  /* margin-top: -15px; */
  /* padding: 10px; */
  /* border-radius: 10px 10px 0 0; */
  background-color: #f2f2f2;
  z-index: 2;
}
.products .tabs{
  display: flex;
  justify-content: space-between;
  font-size: 14px;
  line-height: 3.5;
  background-color: #fff;
}
.products .tabs .item{
  width: 50%;
  text-align: center;
}
.products .tabs .item-cur{
  color: #d50721;
}
.products .tabs .item-bold{
  font-weight: bold;
}
.products .tabs .item:first-child{
  padding-left: 20px;
}
.products .tabs .item:last-child{
  padding-right: 20px;
}
.products .list{
  padding: 10px;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}
.products .list .item{
  width: 49%;
  box-sizing: border-box;
  margin-bottom: 10px;
  border-radius: 6px;
  overflow: hidden;
  background-color: #fff;
}
.products .list .item .img{
  position: relative;
  width: 100%;
  padding-bottom: 100%;
}
.products .list .item img{
  position: absolute;
  width: 100%;
  height: 100%;
  border-radius: 6px 6px 0 0;
}
.products .list .item .name{
  font-size: 14px;
  height: 45px;
  margin-bottom: 2px;
  padding: 8px 10px 3px 10px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  word-break: break-all;
  box-sizing: border-box;
}
.products .list .item .dis{
  font-size: 14px;
  color: #8c8c8c;
  padding: 0 10px 5px 10px;
}
.products .list .item .price{
  display: flex;
  align-items: flex-end;
  padding: 3px 10px 20px 10px;
}
.products .list .item .price h3{
  color: #d50721;
  padding-right: 15px;
}
.products .list .item .price h3 span{
  font-size: 18px;
  padding: 3px;
}
.products .list .item .price h4{
  color: #8c8c8c;
  text-decoration: line-through;
}
.labels{
  position: absolute;
  left: 5px;
  right: 5px;
  bottom: 5px;
  display: flex;
  justify-content: space-between;
}
.labels .label{
  display: block;
  width: 48%;
  height: 25px;
  line-height: 25px;
  font-size: 12px;
  border-radius: 25px;
  color: #ffffff;
  text-align: center;
  box-sizing: border-box;
  background-color: #d50721;
}
.labels .label-cutoff{
  color: #d50721;
  border: 1px solid #d50721;
  background-color: #fff;
}
.products .tabs .item{
  position: relative;
}
.products .tabs .item .arrow{
  position: absolute;
  left: 50%;
  top: 15px;
  margin-left: 32px;
  display: block;
  content: '';
  border: 4px solid;
  border-radius: 2px;
  border-color: transparent transparent #333;
}
.products .tabs .item .dn{
  top: 25px;
  border-color: #333 transparent transparent;
}
.products .tabs .item .up.cur{
  border-color: transparent transparent #d50721;
}
.products .tabs .item .dn.cur{
  border-color: #d50721 transparent transparent;
}
.products .tabs .itemfilter .arrow{
  margin-left: 11px;
  top: 24px;
  transform: rotate(180deg);
  transition: all .2s;
}
.products .tabs .itemfilter .arrow.cur{
  transform: rotate(0deg);
  top: 18px;
  border-color: transparent transparent #333;
}

.filter{
  position: absolute;
  top: 331px; /* 147px; */
  right: 0;
  left: 0;
  bottom: 0;
  border-top: 1px solid #f6f6f6;
  padding: 10px 20px 80px 20px;
  background-color: #fff;
}
.filter .item .sort{
  line-height: 3;
  font-size: 14px;
}
.filter .item .sort-list{
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}
.filter .item .sort-list .item{
  width: 32%;
  margin-right: 2%;
  line-height: 30px;
  margin-bottom: 10px;
  border: 1px solid #dadada;
  text-align: center;
  font-size: 14px;
  box-sizing: border-box;
}
.filter .item .sort-list .itemon{
  color: #fff;
  background-color: #222;
  border-color: #222;
}
.filter .item .sort-list .item:nth-child(3n){
  margin-right: 0;
}
.btns{
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20px 5px 20px 5px;
  background-image: linear-gradient(rgba(255, 255, 255, .6), #ffffff, #ffffff);
}
.close{
  display: none;
  position: absolute;
  right: 20px;
  top: 15px;
  width: 28px;
  height: 28px;
  border-radius: 50%;
  text-align: center;
  line-height: 24px;
  font-size: 24px;
  color: #ccc;
  border: 2px solid #e4e4e4;
}
</style>
<style>
.category-list .product-tabs-outer{
  margin-bottom: 0;
  background-color: #fff!important;
}
</style>